import React, { Component } from "react";
import { Button, Card, message, Table, Modal } from "antd";
import { PlusOutlined, ArrowRightOutlined } from "@ant-design/icons";
import LinkButton from "../../components/link-button/index";
// 引入接口请求函数
import { reqCategorys, reqAddCategory, requpdateCategory } from "../../api";
import AddForm from "./AddForm";
import UpdateForm from "./UpdateForm";
import memoryUtils from "../../utils/memoryUtils";
// 商品分类
export default class Category extends Component {
  state = {
    categorys: [], //一级分类列表
    subCategorys: [], //子集目录
    loading: false, //正在获取数据
    parentId: "0", //设置查询的级别
    parentName: "", //当前的父类名称
    showStatus: 0, //标识添加或更新确认框是否显示 0：都不显示 1:添加 2：更新
  };

  columns = [
    {
      title: "分类名称",
      dataIndex: "name",
      key: "name",
    },
    {
      width: 300,
      title: "操作",
      dataIndex: "",
      key: "",
      render: (category) => (
        <span>
          <LinkButton onClick={() => this.showUpdate(category)}>
            修改分类
          </LinkButton>
          {this.state.parentId === "0" ? (
            <LinkButton
              onClick={() => {
                this.showSubCategorys(category);
              }}
            >
              查看子分类
            </LinkButton>
          ) : null}
        </span>
      ),
    },
  ];

  showSubCategorys = (category) => {
    //更新状态
    this.setState(
      {
        parentId: category.id,
        parentName: category.name,
      },
      () => {
        //状态更新并重新render（）后执行
        this.getCategorys();
      }
    );
  };

  // 获取数据
  getCategorys = async () => {
    const { parentId } = this.state;
    //Ajax获取数据
    this.setState({ loading: true });
    const result = await reqCategorys(parentId);
    this.setState({ loading: false });
    //console.log(result.data);
    if (result.data.status === 0) {
      const categorys = result.data.data;
      //更新状态渲染表格
      if (parentId === "0") {
        //更新一级
        this.setState({ categorys });
      } else {
        //更新二级
        this.setState({ subCategorys: categorys });
      }
    } else {
      message.error("获取分类失败");
    }
  };
  //返回一级标签
  showCategorys = () => {
    //改变状态值
    this.setState({
      parentId: "0",
      parentName: "",
      subCategorys: [],
    });
  };

  //取消模态框
  handleCancel = () => {
    //清除输入数据
    this.from.current.resetFields(["username"]);
    //隐藏确认框
    this.setState({
      showStatus: 0,
    });
  };
  //添加确认框
  showAdd = () => {
    this.setState({
      showStatus: 1,
    });
  };
  //添加分类
  addCategory = async () => {
    console.log("addCategory");
    //隐藏确认框
    this.setState({
      showStatus: 0,
    });
    //收集数据提交请求
    const { parentId, categoryName } = this.from.current.getFieldsValue();
    //重新获取分类列表显示
    //清除输入数据
    this.from.current.resetFields(["username"]);
    const result = await reqAddCategory(categoryName, parentId);
    if (result.status === 0) {
      //重新获取分类列表
      this.getCategorys();
    }
  };
  //更新模态框
  showUpdate = (category) => {
    //保存分类对象
    memoryUtils.title1 = category;
    //console.log(category);
    //更新状态
    this.setState({
      showStatus: 2,
    });
  };
  //更新分类
  updateCategory = async () => {
    //console.log("updateCategory");
    //console.log(this.from);
    //隐藏确定框
    this.setState({
      showStatus: 0,
    });
    //准备数据
    const categoryId = memoryUtils.title1.id;
    // console.log("hyt11", memoryUtils.title1);
    const categoryName = this.from.current.getFieldValue("username");
    console.log("111", this.from.current);
    //清除输入数据
    this.from.current.resetFields(["username"]);
    //发送请求更新
    const result = requpdateCategory({ categoryId, categoryName });
    if (result.status === "0") {
      //重新显示
      this.getCategorys();
    }
  };

  //执行异步任务
  componentDidMount() {
    this.getCategorys();
  }
  render() {
    // 读取状态数据
    const {
      categorys,
      loading,
      subCategorys,
      parentId,
      parentName,
      showStatus,
    } = this.state;
    // 卡片的z左侧
    const title =
      parentId === "0" ? (
        "一级分类列表"
      ) : (
        <span>
          <LinkButton onClick={this.showCategorys}>一级分类列表</LinkButton>
          <ArrowRightOutlined />
          <span>{parentName}</span>
        </span>
      );
    // 右侧信息
    const extra = (
      <Button type="primary" onClick={this.showAdd}>
        <PlusOutlined />
        添加
      </Button>
    );
    return (
      <Card title={title} extra={extra}>
        <Table
          bordered
          dataSource={parentId === "0" ? categorys : subCategorys}
          columns={this.columns}
          pagination={{ defaultPageSize: 5, showQuickJumper: true }}
          loading={loading}
        />

        <Modal
          title="添加分类"
          visible={showStatus === 1}
          onOk={this.addCategory}
          onCancel={this.handleCancel}
        >
          <AddForm
            setForm={(form) => {
              this.from = form;
            }}
            categorys={categorys}
            parentId={parentId}
          />
        </Modal>
        <Modal
          title="更新分类"
          visible={showStatus === 2}
          onOk={this.updateCategory}
          onCancel={this.handleCancel}
        >
          <UpdateForm
            categoryName={memoryUtils.title1.name}
            setForm={(form) => {
              this.from = form;
            }}
          />
        </Modal>
      </Card>
    );
  }
}
